import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

/**
 * 原生 WebSocket 通讯
 *
 * 声明 WebSocket 地址
 * 类似Spring MVC中的 @controller 注解
 * WebSocket 使用 @ServerEndpoint 来进行接口声明
 */
@ServerEndpoint(value = "/websocket/{user}")
public class MyServerEndpoint {

    private static final Logger sysLogger = Logger.getLogger("sysLog");

    // 把上线的用户都存起来
    private static List<Session> userSessions = new ArrayList<>();

    @OnOpen
    public void open(Session session, @PathParam(value = "user") String user) throws IOException {
        // 开启 WebSocket
        sysLogger.info("open ------ WebSocket opened from sessionId " + session.getId());
        try {
            userSessions.add(session);
            session.getBasicRemote().sendText("已经为你打开WebSocket连接~~");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 收到消息时调用的函数
     *
     * @param session
     * @param message
     * @throws IOException
     */
    @OnMessage
    public void onMessage(Session session, String message) throws IOException {
        // 收到 WebSocket 数据
        sysLogger.info("received ------ WebSocket Received from sessionId " + session.getId() + ": " + message);

        // 给当前用户发送信息
        //session.getBasicRemote().sendText(message);

        // 给所有用户发送信息
        for (Session session1 : userSessions) {
            if (session1.isOpen()) {
                session1.getBasicRemote().sendText(message);
            }
        }
    }

    @OnClose
    public void end(Session session) {
        sysLogger.info("closed ------ WebSocket closed from sessionId " + session.getId());
        userSessions.remove(session);
    }

} 
